package com.jiuwei.mylibrary.basefragment

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.viewbinding.ViewBinding
import com.jiuwei.mylibrary.utils.ActivityManager
import com.jiuwei.mylibrary.utils.ImmersiveMode
import com.jiuwei.mylibrary.utils.LightNavigationBar
import com.jiuwei.mylibrary.utils.LightStatusBar
import com.jiuwei.mylibrary.utils.NavigationBarStyle
import com.jiuwei.mylibrary.utils.StatusBarStyle
import com.jiuwei.mylibrary.utils.TopBar
import java.lang.reflect.ParameterizedType

/**
 * 基础Activity类，提供ViewBinding支持和沉浸式状态栏
 * @param VB ViewBinding类型
 */
abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() {

    // ViewBinding实例
    protected lateinit var binding: VB

    // 是否启用沉浸式模式
    protected open val isImmersiveMode: Boolean
        get() {
            // 优先使用新注解
            val immersiveAnnotation = javaClass.getAnnotation(ImmersiveMode::class.java)
            if (immersiveAnnotation != null) {
                return immersiveAnnotation.value
            }
            // 向后兼容旧注解
            val topBarAnnotation = javaClass.getAnnotation(TopBar::class.java)
            return topBarAnnotation?.value ?: false
        }

    // 状态栏是否使用深色图标（true为深色图标，false为浅色图标）
    protected open val isLightStatusBar: Boolean
        get() {
            // 优先使用新注解
            val statusBarStyleAnnotation = javaClass.getAnnotation(StatusBarStyle::class.java)
            if (statusBarStyleAnnotation != null) {
                return statusBarStyleAnnotation.lightIcons
            }
            // 向后兼容旧注解
            val lightStatusBarAnnotation = javaClass.getAnnotation(LightStatusBar::class.java)
            return lightStatusBarAnnotation?.value ?: false
        }

    // 导航栏是否使用深色图标（true为深色图标，false为浅色图标）
    protected open val isLightNavigationBar: Boolean
        get() {
            // 优先使用新注解
            val navigationBarStyleAnnotation = javaClass.getAnnotation(NavigationBarStyle::class.java)
            if (navigationBarStyleAnnotation != null) {
                return navigationBarStyleAnnotation.lightIcons
            }
            // 向后兼容旧注解
            val lightNavigationBarAnnotation = javaClass.getAnnotation(LightNavigationBar::class.java)
            return lightNavigationBarAnnotation?.value ?: false
        }

    // 根布局ID，用于设置系统栏内边距
    protected open val rootViewId: Int = View.NO_ID

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 添加到Activity管理器
        ActivityManager.addActivity(this)
        // 初始化ViewBinding
        initViewBinding()
        // 设置沉浸式模式
        setupImmersiveMode()
        // 初始化视图
        initView()
        // 初始化数据
        initData()
    }

    /**
     * 初始化ViewBinding
     */
    @Suppress("UNCHECKED_CAST")
    private fun initViewBinding() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val clazz = type.actualTypeArguments[0] as Class<VB>
            val method = clazz.getMethod("inflate", LayoutInflater::class.java)
            binding = method.invoke(null, layoutInflater) as VB
            setContentView(binding.root)
        } else {
            throw IllegalArgumentException("泛型参数错误")
        }
    }

    /**
     * 设置沉浸式状态栏
     */
    protected open fun setupImmersiveMode() {
        enableEdgeToEdge()
        // 适配Android Q及以上版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            window.isNavigationBarContrastEnforced = false
        }
        // 适配挖孔屏幕
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            window.attributes.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }
        // 设置状态栏和导航栏样式
        val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView)
        windowInsetsController.isAppearanceLightStatusBars = isLightStatusBar
        windowInsetsController.isAppearanceLightNavigationBars = isLightNavigationBar
        
        // 设置根视图的内边距
        val rootView = findViewById<View>(rootViewId)
        if (rootView != null) {
            ViewCompat.setOnApplyWindowInsetsListener(rootView) { v, insets ->
                val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
                v.setPadding(
                    systemBars.left,
                    if (isImmersiveMode) 0 else systemBars.top,
                    systemBars.right,
                    systemBars.bottom
                )
                insets
            }
        }
    }
    }

    /**
     * 初始化视图，子类实现
     */
    protected abstract fun initView()

    /**
     * 初始化数据，子类可选实现
     */
    protected open fun initData() {}

    override fun onDestroy() {
        super.onDestroy()
        // 从Activity管理器中移除
        ActivityManager.removeActivity(this)
    }
}
